package com.baichang.taoshunda.dao.impl;

import com.baichang.framework.dao.impl.BaseDaoImpl;
import com.baichang.taoshunda.dao.RedPacketHistoryDao;
import com.baichang.taoshunda.entity.RedPacketHistory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by ${wushenglu} on 2018/4/26.
 */
@Repository
public class RedPacketHistoryDaoImpl extends BaseDaoImpl<RedPacketHistory> implements RedPacketHistoryDao {
    /**
     * 获取没有抢的红包信息
     *
     * @param redPacketId
     * @return
     */
    @Override
    public RedPacketHistory getNextRedPacket(Integer redPacketId) {
        String sql = "SELECT * FROM t_red_packet_history WHERE red_id=? AND  ISNULL(user_id) ORDER BY id ASC LIMIT 1 ";
        return queryForBean(sql, redPacketId);
    }

    /**
     * 查询所有抢过的红包记录
     *
     * @param redPacketId
     * @return
     */
    @Override
    public List<Map<String, Object>> findAllHistory(Integer redPacketId) {
        String sql = "SELECT rph.*, u.nick_name AS userName, u.head_pic AS userHeadPic, b.buss_name AS companyName, b.head_pic AS companyHeadPic FROM t_red_packet_history rph INNER JOIN t_user u ON u.id = rph.user_id INNER JOIN t_bussiness b ON b.id = rph.company_id WHERE red_id = ? AND NOT ISNULL(rph.user_id) ORDER BY id ASC ";
        return queryForMapList(sql, redPacketId);
    }

    @Override
    public List<Map<String, Object>> findHistoryByUserId(Integer userId, Integer nowPage, Integer pageSize) {
        String sql = "SELECT rph.id, rph.user_money, rph.company_id, rph.user_id, rph.red_id , rph.user_time, rph.is_max, b.head_pic AS companyHeadPic, b.buss_name AS bussName, rph.is_first FROM t_red_packet_history rph INNER JOIN t_bussiness b ON b.id = rph.company_id WHERE rph.user_id = ?";
        sql += " ORDER BY user_time DESC";
        return listForMapList(sql, nowPage, pageSize, userId);
    }

    /**
     * 查看用户红包个数、手气最佳个数、总计金额、当前金额
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getRedPacketByUserId(Integer userId) {
        String sql = "SELECT ( SELECT COUNT(is_max) FROM t_red_packet_history rp WHERE user_id = ? AND rp.is_max = 1 ) AS maxNumber , ( SELECT COUNT(is_first) FROM t_red_packet_history rph WHERE user_id = ? AND rph.is_first = 1 ) AS firstNumber, IFNULL(SUM(user_money),0) AS allMoney, COUNT(0) AS allNumber FROM t_red_packet_history WHERE user_id = ?";
        return queryForMap(sql, userId, userId, userId);
    }

    @Override
    public Map<String, Object> getUserGetMoneyByIdAndUserId(Integer redPacketId, Integer userId) {
        String sql = "SELECT IFNULL((SELECT  user_money userMoney FROM t_red_packet_history WHERE red_id=? AND user_id=?),0)  AS userMoney";
        return queryForMap(sql, redPacketId, userId);
    }
}
